import datetime
import json

from django.shortcuts import render
from django.views import View
from apps.house.models import House

from django.http import JsonResponse

import logging

from apps.order.models import Order

logger = logging.getLogger('django')
# Create your views here.
from ihome.utils.views import LoginRequiredJSONMixin


class CreateOrderView(LoginRequiredJSONMixin, View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())

        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        user = request.user

        if house.user_id == user.id:
            return JsonResponse({'errno': 4201, 'errmsg': '非法请求或请求次数受限'})

        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        if house.max_days != 0:
            days_live = (end_date - start_date).days
            if days_live > house.max_days or days_live < house.min_days:
                return JsonResponse({'errno': 4201, 'errmsg': '入住时长与房主要求不符'})

        try:
            days = (end_date - start_date).days
            amount = days * house.price

            new_order = Order(
                user=user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount= amount
            )
            new_order.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库读写错误'})

        return JsonResponse({
            "data": {
                "order_id": new_order.id
            },
            "errno": "0",
            "errmsg": "下单成功"
        })


    def get(self, request):

        role = request.GET.get('role')  #【custom: 房客，landlord：房东】

        if not role:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        user = request.user

        try:
            if role == 'custom':
                orders = Order.objects.filter(user=request.user)
            elif role == 'landlord':
                orders = Order.objects.filter(house__user=user)
            else:
                return JsonResponse({'code': 4103, 'errmsg': '参数role有误'})
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库读写错误'})

        try:
            data = []

            for order in orders:
                data.append({
                    "amount": order.amount * 100,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "start_date": order.begin_date,
                    "end_date": order.end_date,
                    "img_url": 'http://www.ihome.site:8080/img/8/1.jpg',
                    "order_id": order.id,
                    "status": order.ORDER_STATUS_CHOICES[order.status][1],
                    "title": order.house.title
                })

        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库读写错误'})

        return JsonResponse({
            "data": {
                "orders": data
            },
            "errmsg": "OK",
            "errno": "0"
        })


class AcceptOrderView(LoginRequiredJSONMixin, View):

    def put(self, request, order_id):

        json_dict = json.loads(request.body.decode())

        action = json_dict.get('action')
        reason = json_dict.get('reason')

        if not action:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        try:
            order = Order.objects.get(id=order_id)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        if action == 'accept':
            try:
                already_orders = Order.objects.filter(house_id=order.house_id,
                                                      status__in=[1, 2, 3, 4])
                begin = order.begin_date
                end = order.end_date
                for already_order in already_orders:
                    if begin <= already_order.begin_date <= end or begin <= already_order.end_date <= end:
                        return JsonResponse({'errno': 4201, 'errmsg': '订单时间冲突'})
            except Exception as e:
                logger.error(e)
                return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

            order.status = 3
            order.save()


        elif action == 'reject':
            order.status = 6
            order.comment = reason
            order.save()
        else:
            return JsonResponse({'code': 4103, 'errmsg': '参数action有误'})

        return JsonResponse({"errno": "0", "errmsg": "操作成功"})


class CommentView(View):

    def put(self, request, order_id):

        json_dict = json.loads(request.body.decode())

        comment = json_dict.get('comment')

        if not comment:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        try:
            order = Order.objects.get(id=order_id)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        if order.status != 3:
            return JsonResponse({'errno': 4201, 'errmsg': '非法请求：该订单不可评论'})

        try:
            order.comment = comment
            order.status = 4
            order.save()
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        return JsonResponse({"errno": "0", "errmsg": "评论成功"})

